package com.gitee.wsl.doc.rss

import kotlin.test.Test
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlin.test.assertEquals

class ConcurrencyTest {
    @Test
    fun parallelParsing() = listOf(Feed.rssV2EnUS, Feed.rssV1Simple, Feed.rssV1Steam)
        .map {
            ParseRSS.parse(it, false) { RSSFeedObject() }
        }.forEach { assertion(it) }

    @Test
    fun concurrentCoroutine() = runBlocking(Dispatchers.Default) {
        repeat(10) {
            println("Step $it")
            coroutineScope {
                listOf(Feed.rssV2EnUS, Feed.rssV1Simple, Feed.rssV1Steam)
                    .map { async { ParseRSS.parse<RSSFeedObject>(it) } }
                    .awaitAll().forEach { assertion(it) }
            }
        }
    }

    private fun assertion(it: RSSFeedObject) = when (it.title) {
        "AAAA - RSS Channel - International Edition" -> {
            assertEquals(it.items[0].title, "Puncak Peringatan Hari Anak Nasional D.I. Yogyakarta 2018" )
            assertEquals(it.items[1].title,"Pemda DIY raih penghargaan pada peringatan HAN 2018 di Surabaya")
        }
        "XML.com" -> {
            assertEquals(it.items[0].title,"Processing Inclusions with XSLT")
            assertEquals(it.items[1].title,"Putting RDF to Work")
        }
        "Steam RSS News Feed" -> {
            assertEquals(it.items[0].title,"Team Fortress 2 Update Released")
            assertEquals(it.items[1].title,"Team Fortress 2 Update Released")
        }
        else -> println("unknown")
    }
}